"use client";
import { useEffect, useRef } from "react";
import { useGlobalErrorStore } from "@/lib/globalErrorStore";
import { XCircle, X } from "lucide-react";

export default function ErrorToast() {
  const { error, clearError } = useGlobalErrorStore();
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (error) {
      timerRef.current = setTimeout(() => {
        clearError();
      }, 3500);
      return () => {
        if (timerRef.current) clearTimeout(timerRef.current);
      };
    }
  }, [error, clearError]);

  if (!error) return null;
  return (
    <div
      className="fixed top-8 left-1/2 z-[9999] -translate-x-1/2 min-w-[320px] max-w-[90vw] bg-white border border-red-200 shadow-lg rounded-lg flex items-start gap-3 px-5 py-4 animate-fade-in-out"
      style={{ boxShadow: "0 4px 24px 0 rgba(255,0,0,0.08)" }}
      role="alert"
      aria-live="assertive"
    >
      <XCircle className="text-red-500 w-6 h-6 mt-0.5 shrink-0" />
      <div className="flex-1 text-red-700 text-base font-medium break-words pr-2">
        {error}
      </div>
      <button
        className="ml-2 text-red-400 hover:text-red-600 transition-colors"
        onClick={clearError}
        aria-label="关闭错误提示"
      >
        <X className="w-5 h-5" />
      </button>
    </div>
  );
}

// tailwindcss: animate-fade-in-out 需在全局样式中定义
// @keyframes fade-in-out { 0%{opacity:0;transform:translateY(-16px);} 10%{opacity:1;transform:translateY(0);} 90%{opacity:1;} 100%{opacity:0;transform:translateY(-16px);} }
// .animate-fade-in-out { animation: fade-in-out 3.5s both; }
